package com.rpframework.module.common.bos.qiniu;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.rpframework.core.json.FailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;


/**
 * 文件上传
 * Created by jump on 2016/8/23.
 */
public class FileHandle {

    private final static String sp = "^";

    protected final Logger log = LoggerFactory.getLogger(getClass());
    private Config config;

    public Config getConfig() {
        return config;
    }

    public void setConfig(Config config) {
        this.config = config;
    }

    /**
     * 文件上传
     *
     * @param file 文件对象
     * @return 上传成功
     */
    public FileUploadResp upload(File file) {
        try {
            UploadManager uploadManager = new UploadManager();
            //调用put方法上传
            Response res = uploadManager.put(file, System.currentTimeMillis() + sp + file.getName(), config.getUploadToken());
            Gson gson = new Gson();
            java.lang.reflect.Type type = new TypeToken<FileUploadResp>() {
            }.getType();
            return gson.fromJson(res.bodyString(), type);
        } catch (QiniuException e) {
            log.error("七牛文件上传失败", log);
            Response r = e.response;
            // 请求失败时打印的异常的信息
            throw new FailException(r.toString());
        }
    }

    /**
     * 获取下载地址
     *
     * @param key 文件名
     * @return 下载地址
     */
    public String getDownloadUrl(String key) {
        return getConfig().auth().privateDownloadUrl(getConfig().getDowDomain() + key, 3600);
    }
}
